package com.universest.swordholder.model
import com.universest.swordholder.aitool.Message
import com.universest.swordholder.aitool.createAiTask
import com.universest.swordholder.data.dao.Passage
import com.universest.swordholder.data.getUserDb
import com.universest.swordholder.data.repository.BookRepository
import com.universest.swordholder.data.repository.LongTextRepository
import com.universest.swordholder.data.repository.PassageRepository
import com.universest.swordholder.data.repository.VolumeRepository
import com.universest.swordholder.model.prompt.PROMPT_SUMMARY
import com.universest.swordholder.model.prompt.PROMPT_SUMMARY_VOLUME
import com.universest.swordholder.task.AbstractTask
import com.universest.swordholder.task.DirectTask
import com.universest.swordholder.task.NeedPrepareTask
import com.universest.swordholder.task.Task
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.takeWhile

/**
 * 小说摘要助手类
 *
 * @param bookId 书籍ID
 */
class NovelSummaryHelper(private val bookId: Int) {

    private val bookRepository = BookRepository(getUserDb())
    private val volumeRepository = VolumeRepository(getUserDb())
    private val passageRepository = PassageRepository(getUserDb())
    private val longTextRepository = LongTextRepository(getUserDb())

    /**
     * 获取指定段落之前的所有非摘要段落
     *
     * @param passageId 段落ID，用于确定获取范围的结束位置
     * @return 在指定段落之前的所有非摘要段落列表
     */
    suspend fun getNonSummaryPassagesBefore(passageId: Int): List<Passage> {
        val passages = mutableListOf<Passage>()
        val passageFlow = getAllPassagesInOrder()
        // 收集指定段落之前的所有段落
        passageFlow.takeWhile { it.passageId != passageId }.collect {
            passages.add(it)
        }
        // 过滤出非摘要段落（没有关联长文本或长文本内容为空的段落）
        return passages.filter {
            if(it.simpleContentId == -1)return@filter true
            val longText = longTextRepository.getTextById(it.simpleContentId).firstOrNull()
            if(longText == null)return@filter true
            if(longText.content.isBlank())return@filter true
            return@filter false
        }
    }

    /**
     * 按顺序获取所有段落的流
     *
     * @return 包含所有段落的Flow对象，按书籍和卷的顺序排列
     */
    fun getAllPassagesInOrder(): Flow<Passage> = flow {
        // 先获取不属于任何卷的段落
        passageRepository.getPassagesByBookIdAndVolumeId(bookId, -1).firstOrNull()?.forEach { emit(it) }
        val volumes = volumeRepository.getVolumeByBookId(bookId).firstOrNull() ?: emptyList()
        // 再按卷的顺序获取各卷中的段落
        volumes.forEach { volume ->
            passageRepository.getPassagesByBookIdAndVolumeId(bookId, volume.volumeId).firstOrNull()?.forEach {
                emit(it)
            }
        }
    }

    fun createSummaryVolumeTask(volumeId:Int,novelInfoHelper: NovelInfoHelper = NovelInfoHelper(bookId)): AbstractTask<Unit, String>{
        return NeedPrepareTask<Unit, String>(
            "生成卷摘要",
            prepareTask = Task("准备生成卷摘要",1){ param->
                updateMessage("正在获取小说信息")
                val novelInfo = novelInfoHelper.getNovelInfo()
                val summaryBefore = novelInfoHelper.getSummaryBeforeVolume(volumeId)
                updateProgress(0,1)
                updateMessage("正在拼接本卷内容")
                val summaries = novelInfoHelper.getSummariesOfVolumePassages(volumeId)
                updateProgress(1,1)
                DirectTask<Unit, List<Message>>(desc = "生成消息列表", obj =
                    PROMPT_SUMMARY_VOLUME.toMessageList(mapOf(
                        "novelInfo" to novelInfo,
                        "previousChapters" to summaryBefore,
                        "currentVolume" to summaries))
                ).combineTask("调用模型",createAiTask("生成卷摘要"))
                    .convert { it.content }
            }
        )
    }

    fun createGenerateSummaryTask(passageId: Int,novelInfoCollector: NovelInfoHelper = NovelInfoHelper(bookId)): AbstractTask<Unit, String>{
        return NeedPrepareTask<Unit, String>(
            "生成摘要",
            prepareTask = Task("准备生成摘要",3){ param->
                updateMessage("正在获取小说信息")
                val novelInfo = novelInfoCollector.getNovelInfo()
                updateProgress(1,3)
                updateMessage("正在获取前文摘要")
                val previousChapterSummaries = novelInfoCollector.getPreviousChapterSummaries(passageId,3, bookId)
                updateMessage("正在获取当前篇章内容")
                updateProgress(2,3)
                val passage = passageRepository.getPassageById(passageId).first()
                val content = """
                    == ${passage?.title} ==
                    
                    ${novelInfoCollector.getPassageContent(passageId)}
                
                """.trimIndent()
                updateProgress(3,3)
                DirectTask<Unit,List<Message>>(desc = "生成消息列表", obj =
                    PROMPT_SUMMARY.toMessageList
                        (mapOf("novelInfo" to novelInfo,
                        "previousChapters" to previousChapterSummaries,
                        "currentChapter" to content)))
                    .combineTask("调用模型", createAiTask("生成摘要"))
                    .convert { it.content }
            },
            prepareMaxProgress = 3,
            taskMaxProgress = 99
        )
    }

}
